﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using Pixysoft.Framework.Noebe.Orm.Core;
using Pixysoft.Framework.Noebe.Orm.Controller;

namespace Pixysoft.Framework.Noebe.Orm
{
    class OrmPagingQuery : IOrmPagingQuery
    {
        IPagingCommand command = null;

        public OrmPagingQuery(IPagingCommand command)
        {
            this.command = command;
        }


        public List<T> SelectAll<T>()
        {
            List<T> list = new List<T>();

            Type targetType = typeof(T);

            string objName = ReflectHelper.GetInterfaceTypeName(targetType);

            string sidName = MappingHelper.GetSysIDName();

            DataTable table = GetAllTable(targetType);

            foreach (DataRow row in table.Rows)
            {
                ObjectProxy proxy = new ObjectProxy(StructStatus.Select, row);

                object returnObj = ConversionController.ProxyToObject(targetType, proxy);

                list.Add((T)returnObj);

            }

            return list;
        }

        private DataTable GetAllTable(Type targetType)
        {
            StringBuilder builder = new StringBuilder();

            string objName = ReflectHelper.GetInterfaceTypeName(targetType);

            string sidName = MappingHelper.GetSysIDName();

            string tablename = MappingHelper.GetTableName(objName);

            command.TableName = tablename;

            if (string.IsNullOrEmpty(command.ColumnName))
                command.ColumnName = sidName;

            return command.ExecuteReader();

        }


        public string Condition
        {
            get { return command.Condition; }
            set { command.Condition = value; }
        }

        public NoebeParameterCollection Parameters
        {
            get { return command.Parameters; }
        }

        public int PageCapacity
        {
            get { return command.PageCapacity; }
            set { command.PageCapacity = value; }
        }

        public int PageIndex
        {
            get { return command.PageIndex; }
            set { command.PageIndex = value; }
        }

        public bool Reverse
        {
            get { return command.Reverse; }
            set { command.Reverse = value; }
        }

        public string OrderBy
        {
            get
            {
                return command.ColumnName;
            }
            set
            {
                command.ColumnName = value;
            }
        }

    }
}
